<style type="text/css">{literal}
.iconDelete {
	background-image: url('/static/img/icons/delete.png');
	background-repeat: no-repeat;
	width: 16px;
	height: 16px;
	text-align: center;
}
.iconAdd {
	background-image: url('/static/img/icons/add.png');
	background-repeat: no-repeat;
	width: 16px;
	height: 16px;
	text-align: center;
}
.iconArrowLeft {
	background-image: url('/static/img/icons/arrow_left.png');
	background-repeat: no-repeat;
	width: 16px;
	height: 16px;
	text-align: center;
}
.iconArrowRight {
	background-image: url('/static/img/icons/arrow_right.png');
	background-repeat: no-repeat;
	width: 16px;
	height: 16px;
	text-align: center;
}
{/literal}</style>

<script type="text/javascript">{literal}
	dojo.require('dojo.data.ItemFileWriteStore');
	dojo.require('dojo.date.locale');
	dojo.require('dojox.grid.DataGrid');
	dojo.require('dijit.Dialog');
	dojo.require('dijit.form.CheckBox');
	dojo.require('dijit.form.Button');
	dojo.require('dijit.form.Form');
	dojo.require('dijit.form.TextBox');
	dojo.require('dijit.form.DateTextBox');
	dojo.require('dijit.form.TimeTextBox');
	dojo.require('dijit.form.FilteringSelect');
	dojo.require('dojox.form.BusyButton');
	dojo.require("dojox.form.FileInput");
	dojo.require("dojox.form.FileInputBlind");
	
	function activeGridFormatter(value, id, obj) {
		var row = obj.grid.getItem(id);
		
		var checkBox = new dijit.form.CheckBox({
			name: 'checkBox',
			value: 'enable',
			checked: value,
			disabled: true,
			onChange: function(b) {
			}
		});
		
		return checkBox;
	}
	
	var visitToDeleteId = null;
	function deleteGridFormatter(value, id, obj) {
		var row = obj.grid.getItem(id);
		
		var button = new dijit.form.Button({
			label: 'Delete',
			showLabel: false,
			iconClass: 'iconDelete',
			onClick: function() {
				dijit.byId('deleteVisitDialog').visitToDeleteId = row.id;
				visitToDeleteId = row.id;
				dijit.byId('deleteVisitDialog').show();
			}
		});
		
		return button;
	}
	
	function dateRangeGridFormatter(value, id, obj) {
		var row = obj.grid.getItem(id);
		if(row.startDate[0] == null) {
			return 'Default Screen (Displayed if no normal visit is active)';
		}
		
		// the substring is to cut of the timezone part of the date (+0100) since dojo does really strange things if
		// one uses proper iso dates ... (for +0100 it adds 1minute 40seconds to the date ...)
		var startDate = dojo.date.stamp.fromISOString(row.startDate[0].substr(0, row.startDate[0].length - 5));
		var endDate = dojo.date.stamp.fromISOString(row.endDate[0].substr(0, row.endDate[0].length - 5));
		
		return dojo.date.locale.format(startDate, {formatLength: 'short'}) + ' - ' + dojo.date.locale.format(endDate, {formatLength: 'short'});
	}
{/literal}</script>

<script type="text/javascript">
var visitsJsonUrl = '{$ro->gen('backend.visits.list')}';
{literal}
var store = new dojo.data.ItemFileWriteStore({url: visitsJsonUrl, clearOnClose: true, urlPreventCache: true});
{/literal}
</script>

<script type="text/javascript">
var templates = {$t.templatesJson};
var fileUploadUrl = '{$ro->gen('backend.visits.uploadFile', array(), array('relative' => false))}';
var visitPreviewUrl = '{$ro->gen('backend.visits.preview')}';

{literal}

function visitFormElementChanged(name, value) {
	console.log("changed: " + name + ": " + value);
	
	// yeah, well, using a single double quote fucks up my syntax highlighting, that is why that regex looks rather strange ;)
	name = name.replace(/""{0}/g, '\\"'); 
	dojo.forEach(dojo.query('#addVisitorForm input[ name = "' + name + '" ]'), function(entry, i) {
		entry.value = value;
		console.log(entry);
	});
}


function addTemplateVariableInputs() {
	var activeTemplateName = dijit.byId('addVisitorTemplateName').attr('value');
	var fieldContainer = dojo.byId('addVisitorAdditionalFields');
	// clear all previously added inputs
	dojo.empty(fieldContainer);

	dojo.forEach(dojo.getObject(activeTemplateName + ".variables", false, templates), function(entry, i) {
		var inputName = 'variables[' + entry.field + ']';
		var inputNodeId = 'addVisit' + entry.field;
		var wrapperNode = dojo.create('input', {type: 'hidden', name: inputName}, fieldContainer);
	});
}

function loadVisitTemplate() {
	dojo.byId('addVisitorPreviewIframe').src = visitPreviewUrl + '?templateName=' + dijit.byId('addVisitorTemplateName').attr('value');
}

function enableOrDisableDateSelectors() {
	var isDefaultVisitCheckbox = dijit.byId('isDefaultVisit');
	var startDateSelector = dijit.byId('startDate');
	var startTimeSelector = dijit.byId('startTime');
	var endDateSelector = dijit.byId('endDate');
	var endTimeSelector = dijit.byId('endTime');
	var disableDateInputs = isDefaultVisitCheckbox.attr('checked');
	startDateSelector.attr('disabled', disableDateInputs);
	startTimeSelector.attr('disabled', disableDateInputs);
	endDateSelector.attr('disabled', disableDateInputs);
	endTimeSelector.attr('disabled', disableDateInputs);
}

function reloadVisitsTimer() {
	var addVisitorDialog = dijit.byId('addVisitorDialog');
	var deleteVisitDialog = dijit.byId('deleteVisitDialog');
	if(!addVisitorDialog.attr('open') && !deleteVisitDialog.attr('open')) {
		store.close();
		store.fetch();
		dijit.byId('visitsGrid')._refresh();
	}
}

function setDateConstraints(refDateId, refTimeId, targetDateId, targetTimeId, constraint) {
	var refDate = dijit.byId(refDateId);
	var refTime = dijit.byId(refTimeId);
	var targetDate = dijit.byId(targetDateId);
	var targetTime = dijit.byId(targetTimeId);
	if(refDate.attr('value')) {
		if(targetDate.attr('value') == null) {
			// target date is not set, use the reference date as default value
			targetDate.attr('value', refDate.attr('value'));
		}
		targetDate.constraints[constraint] = refDate.attr('value');
		if(refDate.attr('value') != null && targetDate.attr('value') != null
		    && refDate.attr('value').getTime() == targetDate.attr('value').getTime()) {
			if(refTime.attr('value') != null) {
				if(targetTime.attr('value') == null) {
					// same date and target time is not set, use the reference time as default value
					targetTime.attr('value', refTime.attr('value'));
				}
				targetTime.constraints[constraint] = refTime.attr('value');
			} else {
				delete targetTime.constraints[constraint];
			}
		} else {
			// if the dates differ just delete all time constraints
			delete refTime.constraints.min;
			delete refTime.constraints.max;
			delete targetTime.constraints.min;
			delete targetTime.constraints.max;
		}
	} else {
		delete targetDate.constraints[constraint];
	}
}

window.setInterval('reloadVisitsTimer()', 60000);


dojo.addOnLoad(addTemplateVariableInputs);
dojo.addOnLoad(loadVisitTemplate);

{/literal}
</script>

<table id="visitsGrid" dojoType="dojox.grid.DataGrid" store="store" style="width: 700px; height: 400px; ">
	<thead>
		<tr>
			<th field="active" formatter="activeGridFormatter" width="50px">Active</th>
			<th field="startDate" formatter="dateRangeGridFormatter" width="200px">Display Date</th>
			<th field="visitorName" width="200px">Visitor</th>
			<th field="lastEditUser" width="100px">Editor</th>
			<th field="delete" formatter="deleteGridFormatter" width="50px">Delete</th>
		</tr>
	</thead>
</table>
<button dojoType="dijit.form.Button" iconClass="iconAdd">
	<script type="dojo/method" event="onClick">
		dijit.byId('addVisitorForm').reset();
		dijit.byId('addVisitorDialog').show();
	</script>
	Add Visitor
</button>

<div id="addVisitorDialog" dojoType="dijit.Dialog" style="width: 860px; height: 480px;">
	<script type="dojo/method" event="onHide">
		dijit.byId('addVisitorForm').reset();
		dijit.byId('addVisitorSubmitButton').cancel();
		loadVisitTemplate();
	</script>
	<form dojoType="dijit.form.Form" id="addVisitorForm" encType="multipart/form-data" action="{$ro->gen('backend.visits.add')}" method="post">
		<input type="hidden" name="visitorName" value="" />
		<div id="addVisitorAdditionalFields" style="display:none"></div>
		
		<button dojoType="dijit.form.Button" iconClass="iconArrowLeft" showLabel="false">
			<script type="dojo/method" event="onClick">
				var tplSelect = dijit.byId('addVisitorTemplateName');
				if(tplSelect.attr('item').previousElementSibling) {
					tplSelect.attr('value', tplSelect.attr('item').previousElementSibling.value);
				}
			</script>
		</button>
		<select dojoType="dijit.form.FilteringSelect" id="addVisitorTemplateName" name="templateName">
			<script type="dojo/method" event="onChange">
				addTemplateVariableInputs();
				loadVisitTemplate();
			</script>
			{foreach $t.templateNames templateName}
			<option value="{$templateName|escape}">{$templateName|escape}</option>
			{/foreach}
		</select>
		<button dojoType="dijit.form.Button" iconClass="iconArrowRight" showLabel="false">
			<script type="dojo/method" event="onClick">
				var tplSelect = dijit.byId('addVisitorTemplateName');
				if(tplSelect.attr('item').nextElementSibling) {
					tplSelect.attr('value', tplSelect.attr('item').nextElementSibling.value);
				}
			</script>
		</button>
		
		<input dojoType="dijit.form.DateTextBox" type="text" name="startDate" id="startDate" required="true" style="width: 100px" onChange="setDateConstraints('startDate', 'startTime', 'endDate', 'endTime', 'min');" />
		<input dojoType="dijit.form.TimeTextBox" type="text" name="startTime" id="startTime" required="true" style="width: 60px" onChange="setDateConstraints('startDate', 'startTime', 'endDate', 'endTime', 'min');" />
		-
		<input dojoType="dijit.form.DateTextBox" type="text" name="endDate" id="endDate" required="true" style="width: 100px"  onChange="setDateConstraints('endDate', 'endTime', 'startDate', 'startTime', 'max');" />
		<input dojoType="dijit.form.TimeTextBox" type="text" name="endTime" id="endTime" required="true" style="width: 60px"  onChange="setDateConstraints('endDate', 'endTime', 'startDate', 'startTime', 'max');" />
		
		<input dojoType="dijit.form.CheckBox" type="checkbox" name="isDefaultVisit" id="isDefaultVisit" required="true" onChange="enableOrDisableDateSelectors();" />
		<label for="isDefaultVisit">Default Screen</label>
		
		<button dojoType="dijit.form.Button" id="addVisitorCancelButton">
			<script type="dojo/method" event="onClick">
				dijit.byId('addVisitorDialog').hide();
			</script>
			Cancel
		</button>
		<button dojoType="dojox.form.BusyButton" type="submit" id="addVisitorSubmitButton" busyLabel="Saving ...">
			<script type="dojo/method" event="onClick">{literal}
				dojo.xhrPost({
					form: 'addVisitorForm',
					handle: function(response, ioArgs) {
						result = dojo.fromJson(response);
						if(result.status == 'success') {
							store.close();
							store.fetch();
							dijit.byId('visitsGrid')._refresh();
							
							dijit.byId('addVisitorDialog').hide();
						} else {
							var hasErrors = false;
							dijit.byId('addVisitorSubmitButton').cancel();
							var errorContainer = dojo.byId('addVisitErrors');
							dojo.empty(errorContainer);
							dojo.forEach(result.errors, function(errorMessage){
								if(errorMessage != null) {
									hasErrors = true;
									// omgomg: poor mans html escaping
									errorMessage = errorMessage.replace('<', '&lt;').replace('>', '&gt;');
									dojo.create('div', {innerHTML: errorMessage}, errorContainer);
								}
							});
							if(!hasErrors) {
								dojo.create('div', {innerHTML: 'Unknwon Error Occured'}, errorContainer);
							}
							
							dijit.byId('addVisitErrorDialog').show();
						}
						
						// return the response for succeeding callbacks
						return response;
					}
				});
				
				return false;
			{/literal}</script>
			Save
		</button>
	</form>
	<iframe id="addVisitorPreviewIframe" src="about:blank" style="width:100%; height: 80%"></iframe>
</div>

<div id="deleteVisitDialog" dojoType="dijit.Dialog" title="Delete entry?">
	<button dojoType="dojox.form.BusyButton" id="deleteVisitButton" busyLabel="Deleting ...">
		<script type="dojo/method" event="onClick">
			var deleteVisitUrl = '{$ro->gen('backend.visits.delete')}';
		{literal}
			dojo.xhrPost({
				url: deleteVisitUrl + '?id=' + dijit.byId('deleteVisitDialog').visitToDeleteId,
				handle: function(response, ioArgs) {
					store.close();
					store.fetch();
					dijit.byId('visitsGrid')._refresh();
					dijit.byId('deleteVisitButton').cancel();
					dijit.byId('deleteVisitDialog').hide();

					// return the response for succeeding callbacks
					return response;
				}
			});
			return false;
		{/literal}</script>
		Yes
	</button>
	<button id="cancelDeleteVisitButton" dojoType="dijit.form.Button">
		<script type="dojo/method" event="onClick">
			dijit.byId('deleteVisitDialog').hide();
		</script>
		No
	</button>
</div>
<div id="addVisitErrorDialog" dojoType="dijit.Dialog" title="An Error Occured">
	<div id="addVisitErrors">
	</div>
</div>
